package com.xiyin.poi.controller;


import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
public class PdfExportController {

    @GetMapping("/export/pdf")
    public ResponseEntity<byte[]> exportToPdf() throws IOException {
        // 加载中文字体（例如：SimSun或Arial Unicode MS）
        PdfFont font = PdfFontFactory.createFont(FontProgramFactory.createFont("D:\\tool\\font\\SimSun-01.ttf"), PdfEncodings.IDENTITY_H, true);

        // 创建内存输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try (PdfWriter writer = new PdfWriter(baos);
             PdfDocument pdfDoc = new PdfDocument(writer)) {

            pdfDoc.setDefaultPageSize(PageSize.A4);

            // 创建布局文档对象
            Document layoutDoc = new Document(pdfDoc);

            // 添加中文内容到PDF
            layoutDoc.add(new Paragraph("你好，这是一个使用iText 7生成的PDF文档！").setFont(font));

            // 关闭布局文档
            layoutDoc.close();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", "sample.pdf");

        return ResponseEntity.ok()
                .headers(headers)
                .body(baos.toByteArray());
    }
}
